#include <stdio.h>
#include <stdlib.h>

typedef struct people{
    int data;
    struct people *next;
}hao;

// 创建循环链表 将 1-n 插入链表中 并返回 1那个节点的地址
hao *create_list_and_insert_data(int n){
    hao *phead = (hao *)malloc(sizeof(hao));
    if(NULL == phead){
        return NULL;
    }
    phead->data = 1;
    phead->next = NULL;
    // 循环将 [2,n] 插入到链表中
    hao *pnew = NULL;
    hao *ptail = phead;
    for(int i = 2; i <= n; i++){
        pnew = (hao *)malloc(sizeof(hao ));
        if(NULL == pnew){
            return NULL;
        }
        pnew->data = i;
        ptail->next = pnew;
        ptail = pnew;
    }
    // 尾节点指针域指向开头  构成循环链表
    ptail->next = phead;
    return phead;
}



int main(int argc, const char *argv[]){
    // 判断执行程序时参数的格式是否正确
    if(3 != argc){
        printf("Usage : %s  总人数  数到几\n", argv[0]);
        return -1;
    }
    // 获取命令行传入的总人数
    int total_person_num = atoi(argv[1]);
    // 获取命令行传入的数到几
    int count = atoi(argv[2]);
    // 判断入参是否合理
    if(total_person_num <= 1 || count <= 1){
        printf("输入的参数不合理  请重新执行\n");
        return -1;
    }

    hao *phead = create_list_and_insert_data(total_person_num);

    // 开始执行淘汰的过程
    int num=0;
    int ci=0;//几次
    hao *p=phead;
    while(phead!=phead->next){
        num++;
        if(num==count){
            printf("这次第%d次 自杀的是第%d号\n",ci,phead->data);
            p->next=phead->next;
            free(phead);
            phead=p->next;
            num=0;
        }else{
            p = phead;
            phead = phead->next;
        }
    }
    printf("最后一个人是%d",phead->data);
    free(phead);
    phead = NULL;
    return 0;
}